package com.fbli.test.controller;

import com.fbli.test.common.entity.user.UserLoginReqMsg;
import com.fbli.test.common.entity.user.UserLoginResMsg;
import com.fbli.test.common.result.ResultParam;
import com.fbli.test.common.result.ResultSend;
import com.fbli.test.entity.User;
import com.fbli.test.service.impl.UserServiceImpl;
import com.fbli.test.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Api(tags = {"用户功能"})
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserServiceImpl userService;
    @GetMapping("/selectAll")
    @RequiresPermissions("admin:user:select")
    public ResultParam selectAll(){
        List<User> users = userService.selectAll();
        return ResultSend.success(users);
    }
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public ResultParam login(HttpServletRequest request, @RequestBody UserLoginReqMsg msg) {
        String account = msg.getAccount();
        String password = msg.getPassword();
        if (StringUtil.isNull(account) || StringUtil.isNull(password)) {
            return ResultSend.fail("账号或密码错误！");
        }
        UserLoginResMsg resMsg = userService.login(account, password, request);
        if (resMsg == null) {
            return ResultSend.fail("账号或密码错误！");
        }
        return ResultSend.success(resMsg);
    }
    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public ResultParam logout() {
        boolean success = userService.logout();
        if (success) {
            return ResultSend.success("退出成功！");
        }
        return ResultSend.fail("退出出错！");
    }
    @ApiOperation("用户新增")
    @PostMapping("/addUser")
    @RequiresPermissions("admin:user:add")
    public ResultParam addUser(@RequestParam("account") String account, @RequestParam("password") String password) {
        boolean success = userService.addUser(account, password);
        if (!success) return ResultSend.fail("添加失败！");
        return ResultSend.success("添加成功！");
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResultParam register(@RequestParam("account") String account, @RequestParam("password") String password) {
        boolean success = userService.addUser(account, password);
        if (!success) return ResultSend.fail("注册失败！");
        return ResultSend.success("注册成功！");
    }
}
